﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Caifu.Clients;
using Itfort.Net;
using Caifu.Pres.Datas;

namespace Caifu.Spiders
{
	/// <summary>
	/// 从金融界抓取。
	/// http://fund.jrj.com.cn/netvalue/
	/// </summary>
	public class GetJrj
	{
		/// <summary>
		/// 运行任务。
		/// </summary>
		public static void RunSpider(DateTime date)
		{
			(new GetJrj()).Crawl(date);
		}

		void Crawl(DateTime date)
		{
			string nvUrl = "http://qf.jrjimg.cn/fund/netvalue/list/open_all.js";
			var html = HttpClient.GetHtml(nvUrl, "gb2312");

			#region 从源代码提取报告日期
			var datePattern = @"enddates:\[(?<date>[\d]*?),[\d]*?\]";
			var dateMatchs = Regex.Matches(html, datePattern);
			if (dateMatchs.Count == 0)
			{
				// 报告问题
			}
			DateTimeFormatInfo format = new DateTimeFormatInfo();
			var dateString = dateMatchs[0].Groups["date"].Value;
			dateString = dateString.Substring(0, 4) + "-" + dateString.Substring(4, 2) + "-" + dateString.Substring(6, 2);
			var tdate = DateTime.Parse(dateString);
			#endregion

			// 目标与期望不符
			if (tdate != date) return;

			var pattern = @"\['(?<code>[\s\S]*?)','(?<name>[\s\S]*?)',([\d]*?),([\d]*?),([\d]*?),([\d]*?),(?<anv>[\d\.]*?),(?<unv>[\d\.]*?),([\s\S]*?),([\s\S]*?),([\s\S]*?),([\s\S]*?),([\d]*?),([\d]*?)\]";
			var matchs = Regex.Matches(html, pattern);

			if (matchs.Count == 0)
			{
				// 报告问题
			}

			foreach (Match match in matchs)
			{
				try
				{
					var fundCode = match.Groups["code"].Value;
					var fundInfo = FundUtil.GetFundByAnyCode(fundCode);
					Guid fundId = Guid.Empty;
					if (fundInfo != null)
					{
						fundId = fundInfo.Id;
						fundCode = fundInfo.Code;
					}

					var unv = Decimal.Parse(match.Groups["unv"].Value);
					var anv = Decimal.Parse(match.Groups["anv"].Value);

					var pnv = NetValuePreClient.GetNetValuePre(fundCode, date);
					if (pnv == null)
					{
						pnv = new NetValuePre();
						pnv.FundId = fundId;
						pnv.FundCode = fundCode;
						pnv.ReportDate = date;

						pnv.UnitNetValue2 = unv;
						pnv.AccumulatedNetValue2 = anv;

						NetValuePreClient.AddNetValuePre(pnv);
					}
					else
					{
						if (pnv.UnitNetValue2 == null || pnv.UnitNetValue2.Value == 0 ||
							pnv.AccumulatedNetValue2 == null || pnv.AccumulatedNetValue2.Value == 0)
						{
							pnv.UnitNetValue2 = unv;
							pnv.AccumulatedNetValue2 = anv;

							NetValuePreClient.UpdateNetValuePre(pnv);
						}
					}
				}
				catch (Exception ex)
				{
					// 报告错误
					Trace.WriteLine(ex.Message + Environment.NewLine
						+ ex.Source + Environment.NewLine
						+ ex.StackTrace);
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="url"></param>
		/// <param name="date"></param>
		/// <returns></returns>
		public static IList<NetValueItem> _Crawl(string url, DateTime date)
		{
			var pattern = @"\['(?<code>[\s\S]*?)','(?<name>[\s\S]*?)',([\d]*?),([\d]*?),([\d]*?),([\d]*?),(?<anv>[\d\.]*?),(?<unv>[\d\.]*?),([\s\S]*?),([\s\S]*?),([\s\S]*?),([\s\S]*?),([\d]*?),([\d]*?)\]";
			CommonSipder spider = new CommonSipder();
			spider.Pattern = pattern;
			spider.IgnoreReportDate = true;
			spider.EnableUnifiedReportDate = true;
			spider.UnifiedReportDatePattern = @"enddates:\[(?<date>[\d]*?),[\d]*?\]";
			return spider.Crawl(url, "gb2312", date);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="date"></param>
		/// <returns></returns>
		public static IList<NetValueItem> _Crawl(DateTime date)
		{
			string url = "http://qf.jrjimg.cn/fund/netvalue/list/open_all.js";
			return _Crawl(url, date);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="date"></param>
		public static void _CrawlAndSave(DateTime date)
		{
			var list = _Crawl(date);
			var preNetValueThirds = Utils.ConvertToPreNetValueThirds(list, "金融界");
			PreNetValueThirdData.Instance.Save(preNetValueThirds);
		}
	}
}
